package com.stox.ui.swing.event;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Enumeration;

import javax.swing.JTextField;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import org.springframework.util.StringUtils;

import com.stox.ui.swing.widget.wrapper.JTree;

public class JTreeSearchTextFieldKeyAdapter extends KeyAdapter {

	private boolean operationInProgress;
	private JTree jtree;
	
	public JTreeSearchTextFieldKeyAdapter(JTree tree) {
		this.jtree = tree;
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		super.keyPressed(e);
		if(!operationInProgress){
			try{
				operationInProgress = true;
				JTextField searchTextField = (JTextField)e.getSource();
				String text = searchTextField.getText()+e.getKeyChar();
				
				DefaultMutableTreeNode node = (DefaultMutableTreeNode)findNode(text);
				if(node != null && node.getPath() != null){
					TreePath path = new TreePath(node.getPath());
					jtree.expandNode(path);
					jtree.setSelectionPath(path);
					jtree.scrollPathToVisible(path);
				}
			}finally{
				operationInProgress = false;
			}
		}
	}
	
	private TreeNode findNode(String text){
		if(StringUtils.hasText(text)){
			TreeNode node = (TreeNode)jtree.getModel().getRoot();
			return findNode(text, node);
		}
		return null;
	}

	private TreeNode findNode(String text, TreeNode node){
		if(node.toString().toUpperCase().contains(text.toUpperCase())){
			return node;
		}
		
		Enumeration<?> enumeration = node.children();
		while(enumeration.hasMoreElements()){
			node = (TreeNode)enumeration.nextElement();
			node = findNode(text, node);
			if(node != null){
				return node;
			}
		}
		return null;
	}
}
